package com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.DoctorChangePriceInfo;
import com.sxfq.loansupermarket.backsystem.modular.logsf.entity.DiscountAudit;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.dao.ConsultantDao;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class ConsultantServiceImpl implements IConsultantService {
    @Autowired
    private ConsultantDao dao;

    @Autowired
    private MemberProductService memberProductService;

    @Autowired
    private SqlMapper sqlMapper;

    @Override
    public List<ConsultantInfo> selectPageListByQueryGetMap(Page<ConsultantInfo> page, SearchConsultantInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartArrivalTime())) {
            params.put("startArrivalTime", searchInfo.getStartArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndArrivalTime())) {
            params.put("endArrivalTime", searchInfo.getEndArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerStatus())) {
            if ("未设置回访".equals(searchInfo.getCustomerStatus())) {
                params.put("customerStatus", "新客首次");
                params.put("firstReturnSettings", '0');
            } else {
                params.put("customerStatus", searchInfo.getCustomerStatus());
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getDiagnosisStatus())) {
            params.put("diagnosisStatus", searchInfo.getDiagnosisStatus());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFieldTc())) {
            params.put("fieldTc", searchInfo.getFieldTc());
        }
        if (StringUtil.isNotEmpty(searchInfo.getTreatmentUnit())) {
            params.put("treatmentUnit", searchInfo.getTreatmentUnit());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFollowStatus())) {
            String followStatus = "";
            String followStatus2[] = searchInfo.getFollowStatus().split(",");
            if (followStatus2.length == 1) {
                followStatus = followStatus2[0];
            } else {
                for (int i = 0; i < followStatus2.length; i++) {
                    if (i == (followStatus2.length - 1)) {
                        followStatus += "'" + followStatus2[i];
                    } else if (i == 0) {
                        followStatus += followStatus2[i] + "'" + ",";
                    } else {
                        followStatus += "'" + followStatus2[i] + "'" + ",";
                    }
                }
            }
            params.put("followStatus", " ('" + followStatus + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getConsumptionStatus())) {
            String consumptionStatus = "";
            String consumptionStatus2[] = searchInfo.getConsumptionStatus().split(",");
            if (consumptionStatus2.length == 1) {
                consumptionStatus = consumptionStatus2[0];
            } else {
                for (int i = 0; i < consumptionStatus2.length; i++) {
                    if (i == (consumptionStatus2.length - 1)) {
                        consumptionStatus += "'" + consumptionStatus2[i];
                    } else if (i == 0) {
                        consumptionStatus += consumptionStatus2[i] + "'" + ",";
                    } else {
                        consumptionStatus += "'" + consumptionStatus2[i] + "'" + ",";
                    }
                }
            }
            params.put("consumptionStatus", " ('" + consumptionStatus + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getDealStatus())) {
            if ("已结账".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已结账'");
            } else if ("已开单".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已开单'");
            } else {
                params.put("dealStatus", "t.deal_status ='未开单'");
            }
        }
        String tableHead = searchInfo.getAbbreviation();
        params.put("tableName", tableHead + "customer_info");
        params.put("tableName1", tableHead + "deal_info");
        params.put("startIndex", searchInfo.getStartIndex());
        params.put("limitIndex", searchInfo.getLimitIndex());
        return dao.getQueryPage(page, params);
    }

    public int getQueryPagesCount(Page<ConsultantInfo> page, SearchConsultantInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartArrivalTime())) {
            params.put("startArrivalTime", searchInfo.getStartArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndArrivalTime())) {
            params.put("endArrivalTime", searchInfo.getEndArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerStatus())) {
            if ("未设置回访".equals(searchInfo.getCustomerStatus())) {
                params.put("customerStatus", "新客首次");
                params.put("firstReturnSettings", '0');
            } else {
                params.put("customerStatus", searchInfo.getCustomerStatus());
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getDiagnosisStatus())) {
            params.put("diagnosisStatus", searchInfo.getDiagnosisStatus());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFieldTc())) {
            params.put("fieldTc", searchInfo.getFieldTc());
        }
        if (StringUtil.isNotEmpty(searchInfo.getTreatmentUnit())) {
            params.put("treatmentUnit", searchInfo.getTreatmentUnit());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFollowStatus())) {
            String followStatus = "";
            String followStatus2[] = searchInfo.getFollowStatus().split(",");
            if (followStatus2.length == 1) {
                followStatus = followStatus2[0];
            } else {
                for (int i = 0; i < followStatus2.length; i++) {
                    if (i == (followStatus2.length - 1)) {
                        followStatus += "'" + followStatus2[i];
                    } else if (i == 0) {
                        followStatus += followStatus2[i] + "'" + ",";
                    } else {
                        followStatus += "'" + followStatus2[i] + "'" + ",";
                    }
                }
            }
            params.put("followStatus", " ('" + followStatus + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getConsumptionStatus())) {
            String consumptionStatus = "";
            String consumptionStatus2[] = searchInfo.getConsumptionStatus().split(",");
            if (consumptionStatus2.length == 1) {
                consumptionStatus = consumptionStatus2[0];
            } else {
                for (int i = 0; i < consumptionStatus2.length; i++) {
                    if (i == (consumptionStatus2.length - 1)) {
                        consumptionStatus += "'" + consumptionStatus2[i];
                    } else if (i == 0) {
                        consumptionStatus += consumptionStatus2[i] + "'" + ",";
                    } else {
                        consumptionStatus += "'" + consumptionStatus2[i] + "'" + ",";
                    }
                }
            }
            params.put("consumptionStatus", " ('" + consumptionStatus + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getDealStatus())) {
            if ("已结账".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已结账'");
            } else if ("已开单".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已开单'");
            } else {
                params.put("dealStatus", "t.deal_status ='未开单'");
            }
        }
        String tableHead = searchInfo.getAbbreviation();
        params.put("tableName", tableHead + "customer_info");
        params.put("tableName1", tableHead + "deal_info");
        return dao.getQueryPagesCount(page, params);
    }

    public ConsultantInfo selectOneById(String consultantId) {
        String sql = "select " +
                "  (CASE a.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,a.* from " + ShiroKit.getUser().getCustomer_info() + " a where id= '" + consultantId + "' limit 1";
        ConsultantInfo info = sqlMapper.selectOne(sql, ConsultantInfo.class);
        return info;
    }

    @Override
    public String selectDealStatus(String reservationsId, String operationTime) {
        String sql = "select id,deal_status from " + ShiroKit.getUser().getDeal_info() + " where reservations_id = '" + reservationsId + "' and operation_time = '" + operationTime + "'";
        List<PayServicedInfo> list = sqlMapper.selectList(sql, PayServicedInfo.class);
        String status = null;
        if (list.size() > 0) {
            status = list.get(0).getDealStatus();
        }
        return status;
    }

    public int update(ConsultantInfo info) {
        return dao.updateById(info);
    }

    public int insert(ConsultantInfo info) {
        String sql1 = "select id,reservations_id from " + ShiroKit.getUser().getCustomer_info() + " where id= '" + info.getId() + "' limit 1";
        ConsultantInfo info1 = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        String sql = "insert into  `tc_diagnosis_info` (`customer_id`,`reservations_id`,`tc_name`,`diagnosis_content`,`diagnosis_time`,outpatient_name) VALUES" +
                "('" + info.getId().trim() + "','" + info1.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','"
                + info.getDiagnosisContent().trim() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName() + "');";
        return sqlMapper.insert(sql);
    }

    public int insert(CustomerInfo info) {
        String sql = "insert into  `tc_diagnosis_info` (`customer_id`,`reservations_id`,`tc_name`,`diagnosis_content`,`diagnosis_time`,outpatient_name) VALUES" +
                "('" + info.getId().trim() + "','" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','"
                + info.getDiagnosisContent().trim() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getOutpatientName() + "');";
        return sqlMapper.insert(sql);
    }

    //批量补欠费
    @Override
    public int repairArrears(String operationTimes, Double arrearsAmount, String reservationsId, String arrearsRemark, String tcName, String customerId, String arrearsOutpatientName) {
        String[] operationTime = operationTimes.split(",");
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String abbreviation = "select id,abbreviation from dept where simplename='" + arrearsOutpatientName + "'";
        Dept dept = sqlMapper.selectOne(abbreviation, Dept.class);
        int result = 0;
        for (int i = 0; i < operationTime.length; i++) {
            String operationTimeStr = operationTime[i];
            String dealSql = "select t.id2 as id2, t.customer_id as customerId,t.reservations_id,t.pay_service_id as payServiceId,t.primary_amount as primaryAmount," +
                    "t.tc_name as tcName,sum(t.arrears) as arrears,t.operation_time as operationTime,t.outpatient_name as outpatientName,t.folding_pay as foldingPay," +
                    "t.pay_service as payService,t.left_up as leftUp,t.left_down as leftDown,t.right_up as rightUp,t.right_down as rightDown,t.doctor as doctor,t.nurse as nurse," +
                    "t.order_discount as orderDiscount,t.pay_service_num as payServiceNum,t.pay_service_numold as payServiceNumold,t.deduction_type as deductionType,t.deduction_typeName as deductionTypeName," +
                    "t.deduction_amount as deductionAmount,t.deposit_amount as depositAmount,sum(t.service_actual_pay) as serviceActualPay,t.discount_hide as " +
                    "discountHide,t.whole_discount as wholeDiscount,t.referraler_person as referralerPerson,t.referraler_personed as referralerPersoned,t.referraler_remarks as referralerRemarks,t.referraler_time as referralerTime  " +
                    "from " + dept.getAbbreviation() + "deal_info t where t.reservations_id = '" + reservationsId + "' and t.operation_time = '" + operationTimeStr + "' group by t.id2";
            List<PayServicedInfo> dealList = sqlMapper.selectList(dealSql, PayServicedInfo.class);
            String time = DateTimeKit.now();
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String referralerPerson = "";
            String referralerPersoned = "";
            String referralerTime = "";
            String referralerRemarks = "";
            for (int j = 0; j < dealList.size(); j++) {
                String id = CommUtils.getUUID();
                PayServicedInfo dealInfo = dealList.get(j);
                if (dealInfo.getReferralerPerson() == null || dealInfo.getReferralerPerson() == "") {
                    referralerPerson = "null";
                } else {
                    referralerPerson = "'" + dealInfo.getReferralerPerson() + "'";
                }
                if (dealInfo.getReferralerPersoned() == null || dealInfo.getReferralerPersoned() == "") {
                    referralerPersoned = "null";
                } else {
                    referralerPersoned = "'" + dealInfo.getReferralerPersoned() + "'";
                }
                if (dealInfo.getReferralerTime() == null || dealInfo.getReferralerTime() == "") {
                    referralerTime = "null";
                } else {
                    referralerTime = "'" + dealInfo.getReferralerTime() + "'";
                }
                if (dealInfo.getReferralerRemarks() == null || dealInfo.getReferralerRemarks() == "") {
                    referralerRemarks = "null";
                } else {
                    referralerRemarks = "'" + dealInfo.getReferralerRemarks() + "'";
                }
                if (arrearsAmount >= dealInfo.getArrears()) {
                    Double arrearsf = 0 - dealInfo.getArrears();
                    String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                            "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up," +
                            "right_down,doctor,nurse,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                            "deduction_amount,deposit_amount,whole_discount," +
                            "discount_hide,primary_amount,referraler_person,referraler_personed,referraler_time,referraler_remarks) values (" +
                            "'" + a4 + id + a3 + "','" + customerId + "','" + dealInfo.getReservationsId() + "','3'," + dealInfo.getPayServiceId() + "," +
                            "'" + tcName + "','" + dealInfo.getArrears() + "','" + arrearsRemark + "','已开单','" + dealInfo.getOperationTime() + "'," +
                            "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0,'" + dealInfo.getPayService() + "','" + arrearsf +
                            "','" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                            "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','" + dealInfo.getId2() + "','" + dealInfo.getOrderDiscount() + "','" + dealInfo.getPayServiceNum() + "','" + dealInfo.getPayServiceNumOld() + "'," +
                            "'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0.00,0.00,'" + dealInfo.getWholeDiscount() + "',0,0," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
                    String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                            "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up," +
                            "right_down,doctor,nurse,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                            "deduction_amount,deposit_amount,whole_discount," +
                            "discount_hide,primary_amount) values (" +
                            "'" + a4 + id + a3 + "','" + customerId + "','" + dealInfo.getReservationsId() + "','3'," + dealInfo.getPayServiceId() + "," +
                            "'" + tcName + "','" + dealInfo.getArrears() + "','" + arrearsRemark + "','已开单','" + dealInfo.getOperationTime() + "'," +
                            "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0,'" + dealInfo.getPayService() + "','" + arrearsf +
                            "','" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                            "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','" + dealInfo.getId2() + "','" + dealInfo.getOrderDiscount() + "','" + dealInfo.getPayServiceNum() + "','" + dealInfo.getPayServiceNumOld() + "'," +
                            "'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0.00,0.00,'" + dealInfo.getWholeDiscount() + "',0,0)";
                    result += sqlMapper.insert(insertSql);
                    result += sqlMapper.insert(insertSql1);
                    arrearsAmount = arrearsAmount - dealInfo.getArrears();
                } else {
                    String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                            "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up," +
                            "right_down,doctor,nurse,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                            "deduction_amount,deposit_amount,whole_discount," +
                            "discount_hide,primary_amount,referraler_person,referraler_personed,referraler_time,referraler_remarks)  values (" +
                            "'" + a4 + id + a3 + "','" + customerId + "','" + dealInfo.getReservationsId() + "','3'," + dealInfo.getPayServiceId() + "," +
                            "'" + tcName + "'," + arrearsAmount + ",'" + arrearsRemark + "','已开单','" + dealInfo.getOperationTime() + "'," +
                            "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0," + dealInfo.getPayService() + ",-" + arrearsAmount +
                            ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                            "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','" + dealInfo.getId2() + "'," + dealInfo.getOrderDiscount() + "," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumOld() + "," +
                            "'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0.00,0.00," + dealInfo.getWholeDiscount() + ",0,0," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
                    String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                            "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up," +
                            "right_down,doctor,nurse,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                            "deduction_amount,deposit_amount,whole_discount," +
                            "discount_hide,primary_amount)  values (" +
                            "'" + a4 + id + a3 + "','" + customerId + "','" + dealInfo.getReservationsId() + "','3'," + dealInfo.getPayServiceId() + "," +
                            "'" + tcName + "'," + arrearsAmount + ",'" + arrearsRemark + "','已开单','" + dealInfo.getOperationTime() + "'," +
                            "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0," + dealInfo.getPayService() + ",-" + arrearsAmount +
                            ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                            "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','" + dealInfo.getId2() + "'," + dealInfo.getOrderDiscount() + "," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumOld() + "," +
                            "'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0.00,0.00," + dealInfo.getWholeDiscount() + ",0,0)";
                    result += sqlMapper.insert(insertSql);
                    result += sqlMapper.insert(insertSql1);
                    arrearsAmount = 0.00;
                }
            }
        }
        return result;
    }

    //批量补欠费
    @Override
    public int repairArrearsYh(List<PaymentInfo> list) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        int result = 0;
        String time = DateTimeKit.now();
        Double arrearsAmount = list.get(0).getArrearsAmount();
        for (int i = 0; i < list.size(); i++) {
            PaymentInfo paymentInfo = list.get(i);
            String dealSql = "select t.id2 as id2, t.customer_id as customerId,t.reservations_id,t.pay_service_id as payServiceId,t.primary_amount as primaryAmount," +
                    "t.tc_name as tcName,sum(t.arrears) as arrears,t.operation_time as operationTime,t.outpatient_name as outpatientName,t.folding_pay as foldingPay," +
                    "t.pay_service as payService,t.left_up as leftUp,t.left_down as leftDown,t.right_up as rightUp,t.right_down as rightDown,t.doctor as doctor,t.nurse as nurse," +
                    "t.order_discount as orderDiscount,t.pay_service_num as payServiceNum,t.pay_service_numold as payServiceNumold,t.deduction_type as deductionType,t.deduction_typeName as deductionTypeName," +
                    "t.deduction_amount as deductionAmount,t.deposit_amount as depositAmount,sum(t.service_actual_pay) as serviceActualPay,t.discount_hide as " +
                    "discountHide,t.whole_discount as wholeDiscount,t.referraler_person as referralerPerson,t.referraler_personed as referralerPersoned,t.referraler_remarks as referralerRemarks,t.referraler_time as referralerTime  " +
                    "from " + ShiroKit.getUser().getDeal_info() + " t where t.reservations_id = '" + paymentInfo.getReservationsId() + "' " +
                    "and t.get_time = '" + paymentInfo.getOperationTime() + "' and id2='" + paymentInfo.getId2() + "' limit 1";
            PayServiceInfo dealInfo = sqlMapper.selectOne(dealSql, PayServiceInfo.class);
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String referralerPerson = "";
            String referralerPersoned = "";
            String referralerTime = "";
            String referralerRemarks = "";
            String id = CommUtils.getUUID();
            if (dealInfo.getReferralerPerson() == null || dealInfo.getReferralerPerson() == "") {
                referralerPerson = "null";
            } else {
                referralerPerson = "'" + dealInfo.getReferralerPerson() + "'";
            }
            if (dealInfo.getReferralerPersoned() == null || dealInfo.getReferralerPersoned() == "") {
                referralerPersoned = "null";
            } else {
                referralerPersoned = "'" + dealInfo.getReferralerPersoned() + "'";
            }
            if (dealInfo.getReferralerTime() == null || dealInfo.getReferralerTime() == "") {
                referralerTime = "null";
            } else {
                referralerTime = "'" + dealInfo.getReferralerTime() + "'";
            }
            if (dealInfo.getReferralerRemarks() == null || dealInfo.getReferralerRemarks() == "") {
                referralerRemarks = "null";
            } else {
                referralerRemarks = "'" + dealInfo.getReferralerRemarks() + "'";
            }
            String deductionTypeId = "";
            String deductionTypeName = "";
            if (paymentInfo.getDeductionType2() == null || paymentInfo.getDeductionType2() == "") {
                deductionTypeId = "null";
                deductionTypeName = "null";
            } else {
                String sql1 = "select * from checkout_method_info a where id='" + paymentInfo.getDeductionType2() + "' limit 1";
                CheckoutMethodInfo checkoutMethodInfo = sqlMapper.selectOne(sql1, CheckoutMethodInfo.class);
                deductionTypeName = "'" + checkoutMethodInfo.getCheckoutMethod() + "'";
                deductionTypeId = "'" + paymentInfo.getDeductionType2() + "'";
            }
            Double deductionAmount = 0.00;
            if (paymentInfo.getDeductionAmount2() == null || paymentInfo.getDeductionAmount2().toString() == "") {
                deductionAmount = 0.00;
            } else {
                deductionAmount = paymentInfo.getDeductionAmount2();
            }
            Double depositAmount = 0.00;
            if (paymentInfo.getDepositAmount2() == null || paymentInfo.getDepositAmount2().toString() == "") {
                depositAmount = 0.00;
            } else {
                depositAmount = paymentInfo.getDepositAmount2();
            }
            Double serviceActualPay = 0.00;
            Double arrears = 0.00;
            if (dealInfo.getArrears() == (deductionAmount + depositAmount)) {   //当前的欠费 等于 抵扣金额
                serviceActualPay = 0.00;   //实收0
                arrears = -(deductionAmount + depositAmount);  //欠费就是储值抵扣加返现抵扣
            }
            if (dealInfo.getArrears() > (deductionAmount + depositAmount)) {    //当前的欠费 大于 抵扣金额
                if (arrearsAmount >= (dealInfo.getArrears() - (deductionAmount + depositAmount))) {   //真实的欠费钱 大于等于 当前的欠费 减 抵扣金额
                    serviceActualPay = dealInfo.getArrears() - (deductionAmount + depositAmount);
                    arrears = -dealInfo.getArrears();
                    arrearsAmount = arrearsAmount - (dealInfo.getArrears() - (deductionAmount + depositAmount));
                    list.get(0).setArrearsAmount(arrearsAmount);    //真实的欠费钱 扣去本个项目收的钱
                } else if (arrearsAmount < (dealInfo.getArrears() - (deductionAmount + depositAmount))) {   //真实的欠费钱 小 当前的欠费 减 抵扣金额
                    serviceActualPay = arrearsAmount;
                    arrears = -(arrearsAmount + deductionAmount + depositAmount);
                    arrearsAmount = 0.00;
                    list.get(0).setArrearsAmount(arrearsAmount);
                } else {
                    serviceActualPay = 0.00;
                    arrears = -(deductionAmount + depositAmount);
                }
            }
            String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                    "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up," +
                    "right_down,doctor,nurse,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                    "deduction_amount,deposit_amount,whole_discount," +
                    "discount_hide,primary_amount,referraler_person,referraler_personed,referraler_time,referraler_remarks)  values (" +
                    "'" + a4 + id + a3 + "','" + paymentInfo.getCustomerId() + "','" + dealInfo.getReservationsId() + "','3'," + dealInfo.getPayServiceId() + "," +
                    "'" + paymentInfo.getTcName() + "'," + serviceActualPay + ",'" + paymentInfo.getArrearsRemarks() + "','已开单','" + dealInfo.getOperationTime() + "'," +
                    "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0," + dealInfo.getPayService() + "," + arrears +
                    ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                    "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','" + dealInfo.getId2() + "'," + dealInfo.getOrderDiscount() + "," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumOld() + "," +
                    "" + deductionTypeId + "," + deductionTypeName + "," + deductionAmount + "," + depositAmount + "," + dealInfo.getWholeDiscount() + ",0,0," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
            String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                    "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up," +
                    "right_down,doctor,nurse,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                    "deduction_amount,deposit_amount,whole_discount," +
                    "discount_hide,primary_amount)  values (" +
                    "'" + a4 + id + a3 + "','" + paymentInfo.getCustomerId() + "','" + dealInfo.getReservationsId() + "','3'," + dealInfo.getPayServiceId() + "," +
                    "'" + paymentInfo.getTcName() + "'," + serviceActualPay + ",'" + paymentInfo.getArrearsRemarks() + "','已开单','" + dealInfo.getOperationTime() + "'," +
                    "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0," + dealInfo.getPayService() + "," + arrears +
                    ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                    "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','" + dealInfo.getId2() + "'," + dealInfo.getOrderDiscount() + "," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumOld() + "," +
                    "" + deductionTypeId + "," + deductionTypeName + "," + deductionAmount + "," + depositAmount + "," + dealInfo.getWholeDiscount() + ",0,0)";
            result += sqlMapper.insert(insertSql);
            result += sqlMapper.insert(insertSql1);
        }
        return result;
    }

    @Override
    public int deleteDealNew(String reservationsId, String operationTime) {
        String discountSql = "select id from t_discount_audit where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "'";
        List<DiscountAudit> list = sqlMapper.selectList(discountSql, DiscountAudit.class);
        if (list.size() > 0) {
            String delDiscount = "delete from t_discount_audit where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "'";
            sqlMapper.delete(delDiscount);
        }
        String sql = "delete from " + ShiroKit.getUser().getDeal_info() + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "'";
        String sql1 = "delete from " + ShiroKit.getUser().getTriage_performance() + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "'";
        sqlMapper.delete(sql1);
        String sql2 = "delete from " + ShiroKit.getUser().getPay_service_members() + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "'";
        sqlMapper.delete(sql2);
        return sqlMapper.delete(sql);
    }

    @Override
    public String insertDealNew(List<PaymentInfo> list) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String time = DateTimeKit.now();
        VipLevelInfo vipLevelInfo = memberProductService.getVipLevel(list.get(0).getReservationsId());
//        Double levelAudit=vipLevelInfo.getDiscountDiscount()*100;
        String dealStatus = "已开单";
        int result = 0;
        Double wholeDiscount = list.get(0).getWholeDiscount();
        int intamount = list.get(0).getIntamount();
        int lowestPriceBill = list.get(0).getLowestPriceBill();
        double d2 = Double.valueOf(ShiroKit.getUser().getLevelTwoAudit());
//        if (wholeDiscount < levelAudit) {
        if (wholeDiscount < d2 || (intamount > 0 && lowestPriceBill == 1)) {
            int discountGrade = 1;
//            if (wholeDiscount >= levelTwoAudit) {
//                discountGrade = 1;
//            } else {
//                discountGrade = 2;
//            }
            String discountId = UUID.randomUUID().toString();
            String discountSql = "insert into t_discount_audit (id,out_patient_name,discount,status,audit_status,customer_id,reservations_id,operation_time,apply_user," +
                    "create_time,discount_grade) values ('" + discountId + "','" + ShiroKit.getUser().getOutpatientName() + "'," + wholeDiscount + ",0,1,'" + list.get(0).getCustomerId() + "'," +
                    "'" + list.get(0).getReservationsId() + "','" + time + "','" + ShiroKit.getUser().getAccount() + "','" + time + "'," + discountGrade + ")";
            sqlMapper.insert(discountSql);
            dealStatus = "待审核";
        }
        for (int i = 0; i < list.size(); i++) {
            PaymentInfo info = list.get(i);
            String id = CommUtils.getUUID();
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String deductionType = info.getDeductionType();
            String deductionTypeName = "";
            String currentSql = "select id,referraler_person,referraler_time,referraler_personed,referraler_remarks from " + ShiroKit.getUser().getCustomer_info() + " t where id='" + info.getCustomerId() + "' limit 1";
            CustomerInfo customerInfo = sqlMapper.selectOne(currentSql, CustomerInfo.class);
            String referralerPerson = "";
            String referralerPersoned = "";
            String referralerTime = "";
            String referralerRemarks = "";
            String doctor = "";
            if (StringUtil.isNotEmpty(customerInfo.getReferralerPerson())) {
                referralerPerson = "'" + customerInfo.getReferralerPerson() + "'";
            } else {
                referralerPerson = "null";
            }
            if (StringUtil.isNotEmpty(info.getDoctor())) {
                doctor = "'" + info.getDoctor() + "'";
            } else {
                doctor = "'未指定医生'";
            }
            if (StringUtil.isNotEmpty(customerInfo.getReferralerPersoned())) {
                referralerPersoned = "'" + customerInfo.getReferralerPersoned() + "'";
            } else {
                referralerPersoned = "null";
            }
            if (StringUtil.isNotEmpty(customerInfo.getReferralerTime())) {
                referralerTime = "'" + customerInfo.getReferralerTime() + "'";
            } else {
                referralerTime = null;
            }
            if (StringUtil.isNotEmpty(customerInfo.getReferralerRemarks())) {
                referralerRemarks = "'" + customerInfo.getReferralerRemarks() + "'";
            } else {
                referralerRemarks = "null";
            }
            if (deductionType != null && !deductionType.equals("") && !deductionType.equals("null")) {
                String checkoutMethodInfoSql = "select id,checkout_method from checkout_method_info where id = '" + info.getDeductionType() + "' limit 1";
                CheckoutMethodInfo checkoutMethodInfo = sqlMapper.selectOne(checkoutMethodInfoSql, CheckoutMethodInfo.class);
                if (checkoutMethodInfo != null) {
                    deductionTypeName = checkoutMethodInfo.getCheckoutMethod();
                }
            }
            if ("null".equals(info.getRemarks()) || StringUtil.isEmpty(info.getRemarks())) {
                info.setRemarks("");
            }
            //查询当前开单人是前台还是Tc
            String sql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='" + tableHead + "' and (c.name ='Tc' or c.name ='Tc主管')  and a.account='" + ShiroKit.getUser().getAccount() + "' " +
                    " and b.simplename= '" + ShiroKit.getUser().getOutpatientName() + "'";
            List<TcInfo> tc = sqlMapper.selectList(sql, TcInfo.class);
            String tcname = ShiroKit.getUser().getAccount();
            if (tc.size() == 0) {
                tcname = "分诊TC";
            }
            if (!"0".equals(info.getVipPayserviceId())) {
                String insert = "insert into " + ShiroKit.getUser().getPay_service_members() + " (pay_service_id,vip_payservice_id,reservations_id,operation_time) " +
                        "values ('" + info.getPayServiceId() + "','" + info.getVipPayserviceId() + "','" + info.getReservationsId() + "','" + time + "')";
                sqlMapper.insert(insert);
            }
            String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                    "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,dental_hygienist,type_number," +
                    "id2,order_discount,pay_service_num,pay_service_numOld," +
                    "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount,referraler_person,referraler_personed,referraler_time,referraler_remarks,no_deal_cause) " +
                    "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "','" + info.getReservationsId() + "','" + info.getPayServiceId() + "','" + tcname + "','',"
                    + info.getServiceActualPay() + ",'" + info.getRemarks() + "','" + dealStatus + "','" + time + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + info.getFoldingPay() + "," + info.getPayService() +
                    "," + info.getArrears() + ",'" + info.getLeftUp() + "','" + info.getLeftDown() + "','" + info.getRightUp() + "','" + info.getRightDown() + "'," + doctor + ",'" + info.getNurse() + "','" + info.getDentalHygienist() + "','','" + a4 + id + a3 + "'," +
                    info.getOrderDiscount() + "," + info.getPayServiceNum() + "," + info.getPayServiceNum() + ",'" + info.getDeductionType() + "','" + deductionTypeName + "'," + info.getDeductionAmount() + "," +
                    "" + info.getDepositAmount() + "," + info.getPrimaryAmount() + "," + info.getDiscountHide() + "," + info.getWholeDiscount() + "," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ",'" + info.getReservationsIdx() + "')";
            String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                    "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,dental_hygienist,type_number," +
                    "id2,order_discount,pay_service_num,pay_service_numOld," +
                    "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount,no_deal_cause) " +
                    "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "','" + info.getReservationsId() + "','" + info.getPayServiceId() + "','" + tcname + "','',"
                    + info.getServiceActualPay() + ",'" + info.getRemarks() + "','" + dealStatus + "','" + time + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + info.getFoldingPay() + "," + info.getPayService() +
                    "," + info.getArrears() + ",'" + info.getLeftUp() + "','" + info.getLeftDown() + "','" + info.getRightUp() + "','" + info.getRightDown() + "'," + doctor + ",'" + info.getNurse() + "','" + info.getDentalHygienist() + "','','" + a4 + id + a3 + "'," +
                    info.getOrderDiscount() + "," + info.getPayServiceNum() + "," + info.getPayServiceNum() + ",'" + info.getDeductionType() + "','" + deductionTypeName + "'," + info.getDeductionAmount() + "," +
                    "" + info.getDepositAmount() + "," + info.getPrimaryAmount() + "," + info.getDiscountHide() + "," + info.getWholeDiscount() + ",'" + info.getReservationsIdx() + "')";
            result += sqlMapper.insert(insertSql);
            sqlMapper.insert(insertSql1);
        }
        return result + "," + time;
    }

    @Override
    public int backAllOrder(List<PaymentInfo> list) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String time = DateTimeKit.now();
        for (int i = 0; i < list.size(); i++) {
            PaymentInfo info = list.get(i);
            String id = CommUtils.getUUID();
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String id2 = info.getId2();
            String referralerPerson = "";
            String referralerPersoned = "";
            String referralerRemarks = "";
            String referralerTime = "";
            String dealSql = "select customer_id as customerId,reservations_id as reservationsId,pay_service_id as payServiceId,tc_name as tcName," +
                    "sum(service_actual_pay) as serviceActualPay,operation_time as operationTime,outpatient_name as outpatientName,sum(folding_pay) as foldingPay," +
                    "pay_service as payService,sum(arrears) as arrears,left_up as leftUp,left_down as leftDown,right_up as rightUp,right_down as rightDown," +
                    "doctor as doctor,nurse as nurse,id2 as id2,order_discount as orderDiscount,pay_service_num as payServiceNum,pay_service_numold as payServiceNumold,sum(deposit_amount) as depositAmount," +
                    "sum(deduction_amount) as deductionAmount,primary_amount as primaryAmount,discount_hide as discountHide,whole_discount as wholeDiscount," +
                    "deduction_type as deductionType,deduction_typeName as deductionTypeName,referraler_person as referralerPerson,referraler_remarks as referralerRemarks,referraler_personed as referralerPersoned,referraler_time as referralerTime " +
                    "from " + ShiroKit.getUser().getDeal_info() + " where id2 = '" + id2 + "' and deal_status='已结账' group by id2 limit 1";
            PaymentInfo dealInfo = sqlMapper.selectOne(dealSql, PaymentInfo.class);
            if (StringUtil.isNotEmpty(dealInfo.getReferralerPerson())) {
                referralerPerson = "'" + dealInfo.getReferralerPerson() + "'";
            } else {
                referralerPerson = "null";
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerPersoned())) {
                referralerPersoned = "'" + dealInfo.getReferralerPersoned() + "'";
            } else {
                referralerPersoned = "null";
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerTime())) {
                referralerTime = "'" + dealInfo.getReferralerTime() + "'";
            } else {
                referralerTime = null;
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerRemarks())) {
                referralerRemarks = "'" + dealInfo.getReferralerRemarks() + "'";
            } else {
                referralerRemarks = "null";
            }
            //查询当前开单人是前台还是Tc
            String sql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='" + tableHead + "' and (c.name ='Tc' or c.name ='Tc主管')  and a.account='" + info.getTcName() + "' " +
                    " and b.simplename= '" + ShiroKit.getUser().getOutpatientName() + "'";
            List<TcInfo> tc = sqlMapper.selectList(sql, TcInfo.class);
            String tcname = info.getTcName();
            if (tc.size() == 0 || "待定TC".equals(info.getTcName())) {
                tcname = "分诊TC";
            }
            if (info.getPayServiceNumST() < dealInfo.getPayServiceNum()) {   //按数量退项目
                Double num = info.getPayServiceNumST() / dealInfo.getPayServiceNum();
                String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                        "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold," +
                        "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount,referraler_person,referraler_personed,referraler_time,referraler_remarks) " +
                        "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" +
                        "" + dealInfo.getPayServiceId() + "','" + tcname + "','',-" + dealInfo.getServiceActualPay() * num + "," +
                        "'" + info.getRemarks() + "','" + info.getDealStatus() + "','" + dealInfo.getOperationTime() + "','" + time + "'," +
                        "'" + ShiroKit.getUser().getOutpatientName() + "',-" + dealInfo.getServiceActualPay() * num + "," + dealInfo.getPayService() +
                        ",-" + dealInfo.getArrears() * num + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "'," +
                        "'" + dealInfo.getRightDown() + "'," +
                        "'" + dealInfo.getDoctor() + "','','','" + dealInfo.getId2() + "',0," + (dealInfo.getPayServiceNum() - info.getPayServiceNumST()) + "," + dealInfo.getPayServiceNumold()
                        + ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "','-" + dealInfo.getDeductionAmount() * num
                        + "',-" + dealInfo.getDepositAmount() * num + ",0,0," + dealInfo.getWholeDiscount() + "," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
                sqlMapper.insert(insertSql);
                String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                        "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold," +
                        "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount) " +
                        "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" + dealInfo.getPayServiceId() + "','" + tcname + "','',-"
                        + dealInfo.getServiceActualPay() * num + ",'" + info.getRemarks() + "','" + info.getDealStatus()
                        + "','" + dealInfo.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName()
                        + "',-" + dealInfo.getServiceActualPay() * num + "," + dealInfo.getPayService() +
                        ",-" + dealInfo.getArrears() * num + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                        "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + (dealInfo.getPayServiceNum() - info.getPayServiceNumST()) + "," + dealInfo.getPayServiceNumold()
                        + ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "','-" + dealInfo.getDeductionAmount() * num
                        + "',-" + dealInfo.getDepositAmount() * num + ",0,0," + dealInfo.getWholeDiscount() + ")";
                sqlMapper.insert(insertSql1);
            } else {
                String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                        "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold," +
                        "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount,referraler_person,referraler_personed,referraler_time,referraler_remarks) " +
                        "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" +
                        "" + dealInfo.getPayServiceId() + "','" + tcname + "','',-" + dealInfo.getServiceActualPay() + "," +
                        "'" + info.getRemarks() + "','" + info.getDealStatus() + "','" + dealInfo.getOperationTime() + "','" + time + "'," +
                        "'" + ShiroKit.getUser().getOutpatientName() + "',-" + dealInfo.getFoldingPay() + "," + dealInfo.getPayService() +
                        ",-" + dealInfo.getArrears() + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "'," +
                        "'" + dealInfo.getRightDown() + "'," +
                        "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumold()
                        + ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "','-" + dealInfo.getDeductionAmount()
                        + "',-" + dealInfo.getDepositAmount() + ",0,0," + dealInfo.getWholeDiscount() + "," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
                sqlMapper.insert(insertSql);
                String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                        "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold," +
                        "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount) " +
                        "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" +
                        "" + dealInfo.getPayServiceId() + "','" + tcname + "','',-" + dealInfo.getServiceActualPay() + "," +
                        "'" + info.getRemarks() + "','" + info.getDealStatus() + "','" + dealInfo.getOperationTime() + "','" + time + "'," +
                        "'" + ShiroKit.getUser().getOutpatientName() + "',-" + dealInfo.getFoldingPay() + "," + dealInfo.getPayService() +
                        ",-" + dealInfo.getArrears() + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "'," +
                        "'" + dealInfo.getRightDown() + "'," +
                        "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumold()
                        + ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "','-" + dealInfo.getDeductionAmount()
                        + "',-" + dealInfo.getDepositAmount() + ",0,0," + dealInfo.getWholeDiscount() + ")";
                sqlMapper.insert(insertSql1);
            }
            //退费 a 退实收金额 先退剩余可划扣业绩 当剩余可划小于0 的时候,退医生业绩表中 已划扣的金额
            String sql3 = "SELECT IFNULL(t2.serviceActualPay, 0) - IFNULL(t3.serviceActualPay, 0) + IFNULL(t2.deposit_amount, 0) AS serviceActualPay," +
                    "t2.customer_id AS customerId,IFNULL(t2.deduction_amounts, 0) - IFNULL(t3.deduction, 0) AS deductionAmount, t2.reservations_id AS reservationsId,t2.id2 " +
                    "FROM (select SUM(w.service_actual_pay) AS serviceActualPay,sum(IF (c.charge_bill_is_docAchievement = 1,w.deduction_amount,0)) AS deduction_amounts," +
                    "SUM(w.deposit_amount) AS deposit_amount,w.id2, w.customer_id, w.reservations_id, w.pay_service_id " +
                    "FROM " + ShiroKit.getUser().getDeal_info() + " w LEFT JOIN checkout_method_info c ON c.id = w.deduction_type WHERE w.id2 = '" + id2 + "' AND  w.deal_status = '已结账' GROUP BY w.id2) t2 LEFT JOIN (select SUM(d.service_actual_pay) AS serviceActualPay, " +
                    "SUM(d.deduction) AS deduction, id2 FROM doctor_change_price d WHERE d.id2 = '" + id2 + "' GROUP BY id2) t3 ON t2.id2 = t3.id2 LEFT JOIN " + ShiroKit.getUser().getPay_service_info() + " t4 " +
                    "ON t2.pay_service_id = t4.id WHERE 1 = 1 limit 1";
            PayServiceInfo payInfo = sqlMapper.selectOne(sql3, PayServiceInfo.class);
            Double serviceActualPayS = payInfo.getServiceActualPay();
            //减去可划扣的金额之后 在退医生业绩
            Double payCount = serviceActualPayS - info.getServiceActualPay();
            Double payCount1 = info.getServiceActualPay() - serviceActualPayS;
            //剩余可退 积分
            Double deductionS = payInfo.getDeductionAmount();
            Double deductionAcount = deductionS - info.getDeductionAmount();
            Double deductionAcount1 = info.getDeductionAmount() - deductionS;
            if (payCount < 0) {
                // 根据ID2 查询医生业绩表创建时间,如果 退款金额t1 > 最后一次创建时间的实收金额t2,则插入一条id2的数据,实收金额为-t2,
                // 而且继续比较 创建时间为倒数第二条的实收金额t3,如果t1-t2 仍旧大于 t3,则插入ID2 ,实收金额为t3 的数据,直到t1 小于轮训时间的实收金额t4,插入t4= t1-t2-t3
                String selectSql = "select service_actual_pay,id2,create_time,update_time,customer_id,reservations_id,doctor,pay_service_name,create_people,update_people,deduction" +
                        ",number,total,arrears,remarks,status from doctor_change_price where id2='" + id2 + "' order by create_time desc ";
                List<DoctorChangePriceInfo> priceInfoList = sqlMapper.selectList(selectSql, DoctorChangePriceInfo.class);
                Double hasFee = 0D;//已经退费的总金额
                if (priceInfoList.size() > 0) {
                    for (DoctorChangePriceInfo priceInfo : priceInfoList) {
                        //划扣实收金额 servicePay
                        Double servicePay = priceInfo.getServiceActualPay();
                        if (servicePay > 0) {
                            if (info.getServiceActualPay() > 0) {
                                if (payCount1 - hasFee > servicePay) {
                                    String insertSql = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','" + (-servicePay) + "','0','" + priceInfo.getNumber() + "','0'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql);
                                    hasFee = hasFee + servicePay;
                                } else {
                                    Double currentFee = payCount1 - hasFee;
                                    String insertSql2 = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','" + (-currentFee) + "','0','" + priceInfo.getNumber() + "','0'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql2);
                                    //退出循环
                                    break;
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }
            if (deductionAcount < 0) {
                String selectSql = "select service_actual_pay,id2,create_time,update_time,customer_id,reservations_id,doctor,pay_service_name,create_people,update_people,deduction" +
                        ",number,total,arrears,remarks,status from doctor_change_price where id2='" + id2 + "' order by create_time desc ";
                List<DoctorChangePriceInfo> priceInfoList = sqlMapper.selectList(selectSql, DoctorChangePriceInfo.class);
                Double hasFeeS = 0D;//已经退积分的总金额
                if (priceInfoList.size() > 0) {
                    for (DoctorChangePriceInfo priceInfo : priceInfoList) {
                        //划扣的积分 servicePayS
                        Double servicePayS = priceInfo.getDeduction();
                        if (servicePayS > 0) {
                            if (info.getDeductionAmount() > 0) {
                                if (deductionAcount1 - hasFeeS > servicePayS) {
                                    String insertSql = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','0','0','" + priceInfo.getNumber() + "','" + (-servicePayS) + "'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql);
                                    hasFeeS = hasFeeS + servicePayS;
                                } else {
                                    Double currentFee = deductionAcount1 - hasFeeS;
                                    String insertSql2 = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','0','0','" + priceInfo.getNumber() + "','" + (-currentFee) + "'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql2);
                                    //退出循环
                                    break;
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }
        }
        return 1;
    }

    @Override
    public int updateDocAchievement(List<PaymentInfo> list) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableNamed = tableHead + "deal_info";
        String tableNametr = tableHead + "triage_performance";
        String time = DateTimeKit.now();
        for (int i = 0; i < list.size(); i++) {
            PaymentInfo info = list.get(i);
            String id = CommUtils.getUUID();
            String id1 = CommUtils.getUUID();
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String id2 = info.getId2();
            String dealSql = "select customer_id as customerId,reservations_id as reservationsId,pay_service_id as payServiceId,tc_name as tcName," +
                    "sum(service_actual_pay) as serviceActualPay,operation_time as operationTime,outpatient_name as outpatientName,sum(folding_pay) as foldingPay," +
                    "pay_service as payService,sum(arrears) as arrears,left_up as leftUp,left_down as leftDown,right_up as rightUp,right_down as rightDown," +
                    "doctor as doctor,nurse as nurse,id2 as id2,order_discount as orderDiscount,pay_service_num as payServiceNum,sum(deposit_amount) as depositAmount," +
                    "sum(deduction_amount) as deductionAmount,deduction_type,deduction_typeName,primary_amount as primaryAmount,discount_hide as discountHide,whole_discount as wholeDiscount " +
                    "from " + tableNamed + " where id2 = '" + id2 + "' group by id2 limit 1";
            PaymentInfo dealInfo = sqlMapper.selectOne(dealSql, PaymentInfo.class);
            //查询当前开单人是前台还是Tc
            String sql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='" + tableHead + "' and (c.name ='Tc' or c.name ='Tc主管')  and a.account='" + ShiroKit.getUser().getAccount() + "'";
            List<TcInfo> tc = sqlMapper.selectList(sql, TcInfo.class);
            String tcname = ShiroKit.getUser().getAccount();
            if (tc.size() == 0) {
                tcname = "分诊TC";
            }
            String insertSql = "insert into " + tableNametr + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                    "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num," +
                    "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount) " +
                    "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" + dealInfo.getPayServiceId() + "','" + tcname + "','',-"
                    + dealInfo.getServiceActualPay() + ",'" + dealInfo.getRemarks() + "','已结账','" + dealInfo.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',-" + dealInfo.getFoldingPay() + "," + dealInfo.getPayService() +
                    ",-" + dealInfo.getArrears() + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                    "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + dealInfo.getPayServiceNum() +
                    ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0,-" + dealInfo.getDepositAmount() + ",0," +
                    "0," + dealInfo.getWholeDiscount() + ")";
            sqlMapper.insert(insertSql);
            String insertSql1 = "insert into " + tableNametr + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                    "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num," +
                    "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount) " +
                    "values ('" + a4 + id1 + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" + dealInfo.getPayServiceId() + "','" + tcname + "','',"
                    + dealInfo.getServiceActualPay() + ",'" + dealInfo.getRemarks() + "','已结账','" + dealInfo.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + dealInfo.getFoldingPay() + "," + dealInfo.getPayService() +
                    "," + dealInfo.getArrears() + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                    "'" + info.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + dealInfo.getPayServiceNum() +
                    ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0," + dealInfo.getDepositAmount() + "," + dealInfo.getPrimaryAmount() + "," +
                    "" + dealInfo.getDiscountHide() + "," + dealInfo.getWholeDiscount() + ")";
            sqlMapper.insert(insertSql1);
            String updateSql = "update " + tableNamed + " set doctor = '" + info.getDoctor() + "' where id2='" + id2 + "';";
            String upddohs = "update hospital_section_statistics set doctor= '" + info.getDoctor() + "' where id2='" + id2 + "' and reservations_id='" + dealInfo.getReservationsId() + "';";
            sqlMapper.update(updateSql);
            sqlMapper.update(upddohs);
        }
        return 1;
    }

    @Override
    public int updateDealDocAchievement(List<PaymentInfo> list) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String time = DateTimeKit.now();
        for (int i = 0; i < list.size(); i++) {
            PaymentInfo info = list.get(i);
            String id = CommUtils.getUUID();
            String id1 = CommUtils.getUUID();
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String id2 = info.getId2();
            String dealSql = "select customer_id as customerId,reservations_id as reservationsId,pay_service_id as payServiceId,tc_name as tcName," +
                    "sum(service_actual_pay) as serviceActualPay,operation_time as operationTime,outpatient_name as outpatientName,sum(folding_pay) as foldingPay," +
                    "pay_service as payService,sum(arrears) as arrears,left_up as leftUp,left_down as leftDown,right_up as rightUp,right_down as rightDown," +
                    "doctor as doctor,nurse as nurse,id2 as id2,order_discount as orderDiscount,pay_service_num as payServiceNum,sum(deposit_amount) as depositAmount," +
                    "sum(deduction_amount) as deductionAmount,deduction_type,deduction_typeName,primary_amount as primaryAmount,discount_hide as discountHide,whole_discount as wholeDiscount " +
                    "from " + ShiroKit.getUser().getDeal_info() + " where id2 = '" + id2 + "' group by id2 limit 1";
            PaymentInfo dealInfo = sqlMapper.selectOne(dealSql, PaymentInfo.class);
            //查询当前开单人是前台还是Tc
            String sql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='" + tableHead + "' and (c.name ='Tc' or c.name ='Tc主管')  and a.account='" + ShiroKit.getUser().getAccount() + "'";
            List<TcInfo> tc = sqlMapper.selectList(sql, TcInfo.class);
            String tcname = ShiroKit.getUser().getAccount();
            if (tc.size() == 0) {
                tcname = "分诊TC";
            }
            String insertSql = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                    "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num," +
                    "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount) " +
                    "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" + dealInfo.getPayServiceId() + "','" + tcname + "','',-"
                    + dealInfo.getServiceActualPay() + ",'" + dealInfo.getRemarks() + "','已结账','" + dealInfo.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',-" + dealInfo.getFoldingPay() + "," + dealInfo.getPayService() +
                    ",-" + dealInfo.getArrears() + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                    "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + dealInfo.getPayServiceNum() +
                    ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0,-" + dealInfo.getDepositAmount() + ",0," +
                    "0," + dealInfo.getWholeDiscount() + ")";
            sqlMapper.insert(insertSql);
            String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler,service_actual_pay,remarks,deal_status,operation_time," +
                    "get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num," +
                    "deduction_type,deduction_typeName,deduction_amount,deposit_amount,primary_amount,discount_hide,whole_discount) " +
                    "values ('" + a4 + id1 + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" + dealInfo.getPayServiceId() + "','" + tcname + "','',"
                    + dealInfo.getServiceActualPay() + ",'" + dealInfo.getRemarks() + "','已结账','" + dealInfo.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + dealInfo.getFoldingPay() + "," + dealInfo.getPayService() +
                    "," + dealInfo.getArrears() + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                    "'" + info.getDoctor() + "','" + dealInfo.getNurse() + "','','" + dealInfo.getId2() + "',0," + dealInfo.getPayServiceNum() +
                    ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0," + dealInfo.getDepositAmount() + "," + dealInfo.getPrimaryAmount() + "," +
                    "" + dealInfo.getDiscountHide() + "," + dealInfo.getWholeDiscount() + ")";
            sqlMapper.insert(insertSql1);
            String updateSql = "update " + ShiroKit.getUser().getDeal_info() + " set doctor = '" + info.getDoctor() + "' where id2='" + id2 + "' and get_time='" + info.getGetTime() + "'";
            sqlMapper.update(updateSql);
        }
        return 1;
    }

    @Override
    public int backAllOrder1(List<PaymentInfo> list) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String time = DateTimeKit.now();
        for (int i = 0; i < list.size(); i++) {
            PaymentInfo info = list.get(i);
            String id = CommUtils.getUUID();
            String a1 = time.replace("-", "");
            String a2 = a1.replace(" ", "");
            String a3 = a2.replace(":", "");
            String a4 = tableHead.replace("_", "");
            String id2 = info.getId2();
            String referralerPerson = "";
            String referralerPersoned = "";
            String referralerRemarks = "";
            String referralerTime = "";
            String dealSql = "select customer_id as customerId,reservations_id as reservationsId,pay_service_id as payServiceId,tc_name as tcName," +
                    "sum(service_actual_pay) as serviceActualPay,operation_time as operationTime,outpatient_name as outpatientName,sum(folding_pay) as foldingPay," +
                    "pay_service as payService,sum(arrears) as arrears,left_up as leftUp,left_down as leftDown,right_up as rightUp,right_down as rightDown," +
                    "doctor as doctor,nurse as nurse,id2 as id2,order_discount as orderDiscount,pay_service_num as payServiceNum,pay_service_numold as payServiceNumold,sum(deposit_amount) as depositAmount," +
                    "sum(deduction_amount) as deductionAmount,referraler_person as referralerPerson,referraler_remarks as referralerRemarks,referraler_personed as referralerPersoned,referraler_time as referralerTime ," +
                    "primary_amount as primaryAmount,discount_hide as discountHide,whole_discount as wholeDiscount,deduction_type as deductionType,deduction_typeName as deductionTypeName " +
                    "from " + ShiroKit.getUser().getDeal_info() + " where id2 = '" + id2 + "' and deal_status='已结账' group by id2 limit 1";
            PaymentInfo dealInfo = sqlMapper.selectOne(dealSql, PaymentInfo.class);
            Double serviceActualPay = info.getServiceActualPay();   //退实收
            Double deductionAmount = info.getDeductionAmount();
            Double foldingPay = 0.00;
            Double depositAmount1 = 0.00;
            Double arrears = dealInfo.getArrears() > 0.00 ? dealInfo.getArrears() : -dealInfo.getArrears(); //取绝对值
            arrears = -arrears;
            String sqlch = "select id,type from checkout_method_info where id='" + dealInfo.getDeductionType() + "' limit 1";
            CheckoutMethodInfo checkoutMethodInfos = new CheckoutMethodInfo();
            CheckoutMethodInfo checkoutMethodInfo = sqlMapper.selectOne(sqlch, CheckoutMethodInfo.class);
            if (checkoutMethodInfo == null) {
                checkoutMethodInfos.setType("0");
                checkoutMethodInfo = checkoutMethodInfos;
            }
            if (dealInfo.getDeductionAmount() > 0 && "2".equals(checkoutMethodInfo.getType())) { //优惠券
                if (serviceActualPay == dealInfo.getServiceActualPay() + dealInfo.getDepositAmount()) {  //退实收等于实际实收
                    deductionAmount = info.getDeductionAmountyhq();   //退优惠券
                    foldingPay = serviceActualPay + info.getDeductionAmountyhq();
                    depositAmount1 = dealInfo.getDepositAmount();
                    serviceActualPay = serviceActualPay - dealInfo.getDepositAmount();  //实收-储值
                } else {
                    foldingPay = serviceActualPay;  //or积分
                    serviceActualPay = serviceActualPay;
                }
            } else if (dealInfo.getDeductionAmount() > 0 && "1".equals(checkoutMethodInfo.getType())) {  //积分
                if (serviceActualPay == dealInfo.getServiceActualPay() + dealInfo.getDepositAmount()) {  //退实收等于实际实收
                    depositAmount1 = dealInfo.getDepositAmount();
                    serviceActualPay = serviceActualPay - dealInfo.getDepositAmount();  //实收-储值
                } else {
                    depositAmount1 = 0.00;
                    serviceActualPay = serviceActualPay;
                }
                deductionAmount = info.getDeductionAmountyhq();   //退优惠券
                foldingPay = serviceActualPay + info.getDeductionAmountyhq();  //or积分

            } else {
                if (serviceActualPay == dealInfo.getServiceActualPay() + dealInfo.getDepositAmount()) {  //退实收等于实际实收
                    depositAmount1 = dealInfo.getDepositAmount();
                    serviceActualPay = serviceActualPay - dealInfo.getDepositAmount();  //实收-储值
                    foldingPay = serviceActualPay;
                } else {
                    //缴费100   储值80  现金20
                    //1 如果退费金额 小于等于 现金   直接退现金，不退储值 2如果退费金额大于 现金   先退现金  然后退储值
                    //100   储值80  现金20  退50
                    if (serviceActualPay >= dealInfo.getServiceActualPay()) {
                        depositAmount1 = serviceActualPay - dealInfo.getServiceActualPay(); // 储值30
                        foldingPay = serviceActualPay;//应收50
                        serviceActualPay = dealInfo.getServiceActualPay();//20
                    } else {
                        depositAmount1 = 0.00;
                        foldingPay = serviceActualPay;
                        //serviceActualPay = dealInfo.getServiceActualPay();
                    }
                }
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerPerson())) {
                referralerPerson = "'" + dealInfo.getReferralerPerson() + "'";
            } else {
                referralerPerson = "null";
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerPersoned())) {
                referralerPersoned = "'" + dealInfo.getReferralerPersoned() + "'";
            } else {
                referralerPersoned = "null";
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerRemarks())) {
                referralerRemarks = "'" + dealInfo.getReferralerRemarks() + "'";
            } else {
                referralerRemarks = "null";
            }
            if (StringUtil.isNotEmpty(dealInfo.getReferralerTime())) {
                referralerTime = "'" + dealInfo.getReferralerTime() + "'";
            } else {
                referralerTime = null;
            }

            //查询当前开单人是前台还是Tc
            String sql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='" + tableHead + "' and (c.name ='Tc' or c.name ='Tc主管')  and a.account='" + info.getTcName() + "'";
            List<TcInfo> tc = sqlMapper.selectList(sql, TcInfo.class);
            String tcname = info.getTcName();
            if (tc.size() == 0 || "待定TC".equals(info.getTcName())) {
                tcname = "分诊TC";
            }
            if (info.getServiceActualPay() > 0) {
                String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler," +
                        "service_actual_pay,remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears," +
                        "left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold," +
                        "deduction_type,deduction_typeName,deposit_amount,primary_amount,discount_hide,whole_discount,deduction_amount,referraler_person,referraler_personed,referraler_time,referraler_remarks) " +
                        "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "'," +
                        "'" + dealInfo.getPayServiceId() + "','" + tcname + "','',-" + serviceActualPay + ",'" + info.getRemarks() + "'," +
                        "'" + info.getDealStatus() + "','" + dealInfo.getOperationTime() + "','" + time + "'," +
                        "'" + ShiroKit.getUser().getOutpatientName() + "',-" + foldingPay + "," + dealInfo.getPayService() + "," + arrears + ",'" + dealInfo.getLeftUp() + "'," +
                        "'" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "','" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + id2 + "'," + dealInfo.getOrderDiscount() + "," +
                        "" + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumold() + ",'" + dealInfo.getDeductionType() + "','"
                        + dealInfo.getDeductionTypeName() + "',-" + depositAmount1 + "," + dealInfo.getPrimaryAmount() + "," +
                        "" + dealInfo.getDiscountHide() + "," + dealInfo.getWholeDiscount() + ",-" + deductionAmount + "," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
                sqlMapper.insert(insertSql);
                String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler," +
                        "service_actual_pay,remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up," +
                        "left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                        "deposit_amount,primary_amount,discount_hide,whole_discount,deduction_amount) " +
                        "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "'," +
                        "'" + dealInfo.getPayServiceId() + "','" + tcname + "','',-" + serviceActualPay + ",'" + info.getRemarks() + "'," +
                        "'" + info.getDealStatus() + "','" + dealInfo.getOperationTime() + "','" + time + "'," +
                        "'" + ShiroKit.getUser().getOutpatientName() + "',-" + foldingPay + "," + dealInfo.getPayService() +
                        "," + arrears + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "'," +
                        "'" + dealInfo.getRightDown() + "','" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + id2 + "'," + dealInfo.getOrderDiscount() + "," +
                        "" + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumold() + ",'" + dealInfo.getDeductionType() + "','"
                        + dealInfo.getDeductionTypeName() + "',-" + depositAmount1 + "," + dealInfo.getPrimaryAmount() + "," +
                        "" + dealInfo.getDiscountHide() + "," + dealInfo.getWholeDiscount() + ",-" + deductionAmount + ")";
                sqlMapper.insert(insertSql1);
            } else {
                Double arrearsAmount = dealInfo.getArrears();
                if (arrearsAmount > 0) {
                    String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler," +
                            "service_actual_pay,remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears," +
                            "left_up,left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold," +
                            "deduction_type,deduction_typeName,deposit_amount,primary_amount,discount_hide,whole_discount,deduction_amount,referraler_person,referraler_personed,referraler_time,referraler_remarks) " +
                            "values ('" + a4 + id + a3 + "','" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "'," +
                            "'" + dealInfo.getPayServiceId() + "','" + tcname + "','',0,'" + info.getRemarks() + "','" + info.getDealStatus() + "'," +
                            "'" + dealInfo.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," +
                            "0," + dealInfo.getPayService() + ",-" + arrearsAmount + ",'" + dealInfo.getLeftUp() + "'," +
                            "'" + dealInfo.getLeftDown() + "','" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "'," +
                            "'" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + id2 + "'," + dealInfo.getOrderDiscount() + "," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumold() +
                            ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0,0,0," + dealInfo.getWholeDiscount() + ",-" + deductionAmount + "," + referralerPerson + "," + referralerPersoned + "," + referralerTime + "," + referralerRemarks + ")";
                    sqlMapper.insert(insertSql);
                    String insertSql1 = "insert into " + ShiroKit.getUser().getTriage_performance() + " (id,customer_id,is_do,reservations_id,pay_service_id,tc_name,referraler," +
                            "service_actual_pay,remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up," +
                            "left_down,right_up,right_down,doctor,nurse,type_number,id2,order_discount,pay_service_num,pay_service_numold,deduction_type,deduction_typeName," +
                            "deposit_amount,primary_amount,discount_hide,whole_discount,deduction_amount) values ('" + a4 + id + a3 + "'," +
                            "'" + info.getCustomerId() + "',4,'" + dealInfo.getReservationsId() + "','" + dealInfo.getPayServiceId() + "'," +
                            "'" + tcname + "','',0,'" + info.getRemarks() + "','" + info.getDealStatus() + "','" + dealInfo.getOperationTime() + "'," +
                            "'" + time + "','" + ShiroKit.getUser().getOutpatientName() + "',0," +
                            "" + dealInfo.getPayService() + ",-" + arrearsAmount + ",'" + dealInfo.getLeftUp() + "','" + dealInfo.getLeftDown() + "'," +
                            "'" + dealInfo.getRightUp() + "','" + dealInfo.getRightDown() + "','" + dealInfo.getDoctor() + "','" + dealInfo.getNurse() + "','','" + id2 + "'," +
                            "" + dealInfo.getOrderDiscount() + "," + dealInfo.getPayServiceNum() + "," + dealInfo.getPayServiceNumold()
                            + ",'" + dealInfo.getDeductionType() + "','" + dealInfo.getDeductionTypeName() + "',0,0,0," + dealInfo.getWholeDiscount()
                            + ",-" + deductionAmount + ")";
                    sqlMapper.insert(insertSql1);
                }
            }
            //退费 a 退实收金额 先退剩余可划扣业绩 当剩余可划小于0 的时候,退医生业绩表中 已划扣的金额
            String sql3 = "SELECT IFNULL(t2.serviceActualPay, 0) - IFNULL(t3.serviceActualPay, 0) + IFNULL(t2.deposit_amount, 0) AS serviceActualPay," +
                    "t2.customer_id AS customerId,IFNULL(t2.deduction_amounts, 0) - IFNULL(t3.deduction, 0) AS deductionAmount, t2.reservations_id AS reservationsId,t2.id2 " +
                    "FROM (select SUM(w.service_actual_pay) AS serviceActualPay,sum(IF (c.charge_bill_is_docAchievement = 1,w.deduction_amount,0)) AS deduction_amounts," +
                    "SUM(w.deposit_amount) AS deposit_amount,w.id2, w.customer_id, w.reservations_id, w.pay_service_id " +
                    "FROM " + ShiroKit.getUser().getDeal_info() + " w LEFT JOIN checkout_method_info c ON c.id = w.deduction_type WHERE w.id2 = '" + id2 + "' AND  w.deal_status = '已结账' GROUP BY w.id2) t2 LEFT JOIN (select SUM(d.service_actual_pay) AS serviceActualPay, " +
                    "SUM(d.deduction) AS deduction, id2 FROM doctor_change_price d WHERE d.id2 = '" + id2 + "' GROUP BY id2) t3 ON t2.id2 = t3.id2 LEFT JOIN " + ShiroKit.getUser().getPay_service_info() + " t4 " +
                    "ON t2.pay_service_id = t4.id WHERE 1 = 1 limit 1";
            PayServiceInfo payInfo = sqlMapper.selectOne(sql3, PayServiceInfo.class);
            Double serviceActualPayS = payInfo.getServiceActualPay();
            //减去可划扣的金额之后 在退医生业绩
            Double payCount = serviceActualPayS - info.getServiceActualPay();
            Double payCount1 = info.getServiceActualPay() - serviceActualPayS;
            //剩余可退 积分
            Double deductionS = payInfo.getDeductionAmount();
            Double deductionAcount = deductionS - info.getDeductionAmount();
            Double deductionAcount1 = info.getDeductionAmount() - deductionS;
            if (payCount < 0) {
                // 根据ID2 查询医生业绩表创建时间,如果 退款金额t1 > 最后一次创建时间的实收金额t2,则插入一条id2的数据,实收金额为-t2,
                // 而且继续比较 创建时间为倒数第二条的实收金额t3,如果t1-t2 仍旧大于 t3,则插入ID2 ,实收金额为t3 的数据,直到t1 小于轮训时间的实收金额t4,插入t4= t1-t2-t3
                String selectSql = "select service_actual_pay,id2,create_time,update_time,customer_id,reservations_id,doctor,pay_service_name,create_people,update_people,deduction" +
                        ",number,total,arrears,remarks,status from doctor_change_price where id2='" + id2 + "' order by create_time desc ";
                List<DoctorChangePriceInfo> priceInfoList = sqlMapper.selectList(selectSql, DoctorChangePriceInfo.class);
                Double hasFee = 0D;//已经退费的总金额
                if (priceInfoList.size() > 0) {
                    for (DoctorChangePriceInfo priceInfo : priceInfoList) {
                        //划扣实收金额 servicePay
                        Double servicePay = priceInfo.getServiceActualPay();
                        if (servicePay > 0) {
                            if (info.getServiceActualPay() > 0) {
                                if (payCount1 - hasFee > servicePay) {
                                    String insertSql = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','" + (-servicePay) + "','0','" + priceInfo.getNumber() + "','0'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql);
                                    hasFee = hasFee + servicePay;
                                } else {
                                    Double currentFee = payCount1 - hasFee;
                                    String insertSql2 = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','" + (-currentFee) + "','0','" + priceInfo.getNumber() + "','0'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql2);
                                    //退出循环
                                    break;
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }
            if (deductionAcount < 0) {
                String selectSql = "select service_actual_pay,id2,create_time,update_time,customer_id,reservations_id,doctor,pay_service_name,create_people,update_people,deduction" +
                        ",number,total,arrears,remarks,status from doctor_change_price where id2='" + id2 + "' order by create_time desc ";
                List<DoctorChangePriceInfo> priceInfoList = sqlMapper.selectList(selectSql, DoctorChangePriceInfo.class);
                Double hasFeeS = 0D;//已经退积分的总金额
                if (priceInfoList.size() > 0) {
                    for (DoctorChangePriceInfo priceInfo : priceInfoList) {
                        //划扣的积分 servicePayS
                        Double servicePayS = priceInfo.getDeduction();
                        if (servicePayS > 0) {
                            if (info.getDeductionAmount() > 0) {
                                if (deductionAcount1 - hasFeeS > servicePayS) {
                                    String insertSql = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','0','0','" + priceInfo.getNumber() + "','" + (-servicePayS) + "'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql);
                                    hasFeeS = hasFeeS + servicePayS;
                                } else {
                                    Double currentFee = deductionAcount1 - hasFeeS;
                                    String insertSql2 = "insert into doctor_change_price (id2,doctor,customer_id,reservations_id,pay_service_name,service_actual_pay,arrears,number,deduction,remarks,update_time,create_time,update_people,create_people,status)" +
                                            " VALUES('" + id2 + "','" + priceInfo.getDoctor() + "','" + priceInfo.getCustomerId() + "','" + priceInfo.getReservationsId() + "','" + priceInfo.getPayServiceName() + "','0','0','" + priceInfo.getNumber() + "','" + (-currentFee) + "'," +
                                            "'" + priceInfo.getRemarks() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "','" + priceInfo.getCreatePeople() + "','0')";
                                    sqlMapper.insert(insertSql2);
                                    //退出循环
                                    break;
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }

        }
        return 1;
    }

    public int insertReturnVisit(CustomerInfo info) {
        String sql1 = "select id from " + ShiroKit.getUser().getCustomer_info() + " where arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null " +
                " and reservations_id= '" + info.getReservationsId() + "' limit 0,1 ";
        ConsultantInfo info1 = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        if (info1 != null) {
            String sql = "insert into `return_visit_info` (`reservations_id`,`revisit`,`outpatient_name`, `revisit_content`,`revisit_time`) VALUES" +
                    "('" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                    + info.getRevisitContent() + "','" + DateTimeKit.now() + "');";
            return sqlMapper.insert(sql);
        } else {
            String sqlselecthf = "select id,outpatient_name from reservations_info a where a.id='" + info.getReservationsId() + "' limit 0,1 ";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlselecthf, ReservationsInfo.class);
            if (reservationsInfo != null) {
                String sql = "insert into `return_visit_info` (`reservations_id`,`revisit`,`outpatient_name`, `revisit_content`,`revisit_time`) VALUES" +
                        "('" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','" + reservationsInfo.getOutpatientName() + "','"
                        + info.getRevisitContent() + "','" + DateTimeKit.now() + "');";
                return sqlMapper.insert(sql);
            } else {
                String sql = "insert into `return_visit_info` (`reservations_id`,`revisit`,`outpatient_name`, `revisit_content`,`revisit_time`) VALUES" +
                        "('" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                        + info.getRevisitContent() + "','" + DateTimeKit.now() + "');";
                return sqlMapper.insert(sql);
            }
        }
    }

    public int insertReturnVisits(CustomerInfo info) {
        String sql1 = "select id from " + ShiroKit.getUser().getCustomer_info() + " where arrival_status!=1 and arrival_status!=6 and arrival_status!=7 and arrival_status!=8 and arrival_status!=9 and arrival_status!=10 and arrival_time is not null " +
                " and reservations_id= '" + info.getReservationsId() + "' limit 0,1 ";
        ConsultantInfo info1 = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        if (info1 != null) {
            String sql = "insert into `return_visit_info` (`reservations_id`,`revisit`,`outpatient_name`, `revisit_content`,`revisit_time`) VALUES" +
                    "('" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                    + info.getRevisitContent() + "','" + DateTimeKit.now() + "');";
            String insql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                    "outpatient_name,tc_name,remarks,create_name,revisit_status,follow_status,consumption_status) values ('" + info.getReservationsId()
                    + "','" + info1.getId() + "','" + ShiroKit.getUser().getAccount() + "'," + info.getAppointmentTime() + ",'" + ShiroKit.getUser().getOutpatientName()
                    + "','" + ShiroKit.getUser().getAccount() + "','" + info.getRevisitContent() + "','" + ShiroKit.getUser().getAccount() + "'" +
                    ",'" + info.getRevisitStatus1() + "','" + info.getFollowStatus1() + "','" + info.getConsumptionStatus1() + "')";
            sqlMapper.insert(insql);
            return sqlMapper.insert(sql);
        } else {
            String sqlselecthf = "select id,outpatient_name from reservations_info a where a.id='" + info.getReservationsId() + "' limit 0,1 ";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlselecthf, ReservationsInfo.class);
            if (reservationsInfo != null) {
                String sql = "insert into `return_visit_info` (`reservations_id`,`revisit`,`outpatient_name`, `revisit_content`,`revisit_time`) VALUES" +
                        "('" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','" + reservationsInfo.getOutpatientName() + "','"
                        + info.getRevisitContent() + "','" + DateTimeKit.now() + "');";
                String insql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                        "outpatient_name,tc_name,revisit_content,create_name,revisit_status,follow_status,consumption_status) values ('" + info.getReservationsId()
                        + "','" + reservationsInfo.getId() + "','" + ShiroKit.getUser().getAccount() + "'," + info.getAppointmentTime() + ",'" + ShiroKit.getUser().getOutpatientName()
                        + "','" + ShiroKit.getUser().getAccount() + "','" + info.getRevisitContent() + "','" + ShiroKit.getUser().getAccount() + "'" +
                        ",'" + info.getRevisitStatus1() + "','" + info.getFollowStatus1() + "','" + info.getConsumptionStatus1() + "')";
                sqlMapper.insert(insql);
                return sqlMapper.insert(sql);
            } else {
                String sql = "insert into `return_visit_info` (`reservations_id`,`revisit`,`outpatient_name`, `revisit_content`,`revisit_time`) VALUES" +
                        "('" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                        + info.getRevisitContent() + "','" + DateTimeKit.now() + "');";
                String insql = "insert into return_tc_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                        "outpatient_name,tc_name,revisit_content,create_name,revisit_status,follow_status,consumption_status) values ('" + info.getReservationsId()
                        + "','" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "'," + info.getAppointmentTime() + ",'" + ShiroKit.getUser().getOutpatientName()
                        + "','" + ShiroKit.getUser().getAccount() + "','" + info.getRevisitContent() + "','" + ShiroKit.getUser().getAccount() + "'" +
                        ",'" + info.getRevisitStatus1() + "','" + info.getFollowStatus1() + "','" + info.getConsumptionStatus1() + "')";
                sqlMapper.insert(insql);
                return sqlMapper.insert(sql);
            }
        }
    }

    public int updateDiagnosisStatus(String reservationsId) {
        String sql = "update " + ShiroKit.getUser().getCustomer_info() + " set diagnosis_status='已看诊' where reservations_id='" + reservationsId + "'";
        return sqlMapper.update(sql);
    }

    //删除开单信息
    @Override
    public int deleteOrder(String customerId, String reservationsId, String operationTime, String getTime) {
        String discountAuditSql = "select id from t_discount_audit where customer_id = '" + customerId + "' and reservations_id " +
                "= '" + reservationsId + "' and operation_time = '" + operationTime + "'";
        List discountList = sqlMapper.selectList(discountAuditSql, DiscountAudit.class);
        if (discountList.size() > 0) {
            String delDiscount = "delete from t_discount_audit where customer_id = '" + customerId + "' and reservations_id " +
                    "= '" + reservationsId + "' and operation_time = '" + operationTime + "'";
            sqlMapper.delete(delDiscount);
        }
        String delSql = "delete from " + ShiroKit.getUser().getDeal_info() + " where customer_id = '" + customerId + "' and reservations_id = '" + reservationsId + "' and get_time = '" + getTime + "'";
        String delSql1 = "delete from " + ShiroKit.getUser().getTriage_performance() + " where customer_id = '" + customerId + "' and reservations_id = '" + reservationsId + "' and get_time = '" + getTime + "'";
        sqlMapper.delete(delSql1);
        String sql2 = "delete from " + ShiroKit.getUser().getPay_service_members() + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "'";
        sqlMapper.delete(sql2);
        sqlMapper.delete(delSql);
        String insql = "INSERT INTO `delete_order_info` (`delete_user`, `reservations_id`) VALUES " +
                "('" + ShiroKit.getUser().getName() + "', '" + reservationsId + "');";
        return sqlMapper.insert(insql);
    }

    //整单补欠款
    @Override
    public Map<String, Object> commitArrears(Map<String, Object> map) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Double arrearsAmount = Double.parseDouble(map.get("arrearsAmount").toString());
        String operationTime = map.get("operationTime") + "";
        String reservationsId = map.get("reservationsId") + "";
        String tcName = map.get("tcName") + "";
        String doctor = map.get("doctor") + "";
        String remark = map.get("remark") + "";
        String dealSql = "select t.id2 as id2,sum(t.arrears) as arrears from " + ShiroKit.getUser().getDeal_info() + " t where t.operation_time = '" + operationTime + "' and t.reservations_id = '" + reservationsId + "' group by t.id2";
        List<PayServicedInfo> payServiceList = sqlMapper.selectList(dealSql, PayServicedInfo.class);
        int result = 0;
        Double totalArrears = 0.00;
        for (int i = 0; i < payServiceList.size(); i++) {
            totalArrears += payServiceList.get(i).getArrears();
        }
        if (totalArrears > 0) {
            String time = DateTimeKit.now();
            for (int i = 0; i < payServiceList.size(); i++) {
                PayServicedInfo payService = payServiceList.get(i);
                String id2 = payService.getId2();
                String dealInfo = "select * from " + ShiroKit.getUser().getDeal_info() + " t where t.id = '" + id2 + "' limit 1";
                PayServiceInfo deal = sqlMapper.selectOne(dealInfo, PayServiceInfo.class);
                String UUID = CommUtils.getUUID();
                String a1 = time.replace("-", "");
                String a2 = a1.replace(" ", "");
                String a3 = a2.replace(":", "");
                String a4 = tableHead.replace("_", "");
                if (payService.getArrears() > 0) {
                    Double arrears = payService.getArrears();
                    if (arrearsAmount >= arrears) {
                        Double repairArrearsAmount = arrearsAmount - arrears;
                        String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                                "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down," +
                                "doctor,id2,order_discount,pay_service_num,deduction_type,primary_amount,discount_hide,whole_discount,deduction_typeName,deduction_amount," +
                                "deposit_amount) values ('" + a4 + UUID + a3 + "'," +
                                "'" + deal.getCustomerId() + "','" + deal.getReservationsId() + "','3','" + deal.getPayServiceId() + "','" + tcName + "'," + arrears + ",'" + remark + "'," +
                                "'已开单','" + deal.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + deal.getFoldingPay() + "," +
                                "" + deal.getPayService() + ",-" + arrears + ",'" + deal.getLeftUp() + "','" + deal.getLeftDown() + "','" + deal.getRightUp() + "','" + deal.getRightDown() + "'," +
                                "'" + doctor + "','" + deal.getId2() + "'," + deal.getOrderDiscount() + "," + deal.getPayServiceNum() + ",''," + deal.getPrimaryAmount() + "," +
                                "" + deal.getDiscountHide() + "," + deal.getWholeDiscount() + ",'',0.00,0.00)";
                        result += sqlMapper.insert(insertSql);
                        arrearsAmount = arrearsAmount - arrears;
                    } else {
                        String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                                "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down," +
                                "doctor,id2,order_discount,pay_service_num,deduction_type,primary_amount,discount_hide,whole_discount,deduction_typeName," +
                                "deduction_amount,deposit_amount) values ('" + a4 + UUID + a3 + "'," +
                                "'" + deal.getCustomerId() + "','" + deal.getReservationsId() + "','3','" + deal.getPayServiceId() + "','" + tcName + "'," + arrearsAmount + ",'" + remark + "'," +
                                "'已开单','" + deal.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + deal.getFoldingPay() + "," +
                                "" + deal.getPayService() + ",-" + arrearsAmount + ",'" + deal.getLeftUp() + "','" + deal.getLeftDown() + "','" + deal.getRightUp() + "','" + deal.getRightDown() + "'," +
                                "'" + doctor + "','" + deal.getId2() + "'," + deal.getOrderDiscount() + "," + deal.getPayServiceNum() + ",''," + deal.getPrimaryAmount() + "," +
                                "" + deal.getDiscountHide() + "," + deal.getWholeDiscount() + ",'',0.00,0.00)";
                        result += sqlMapper.insert(insertSql);
                        arrearsAmount = 0.00;
                    }
                } else {
                    Double repairArrearsAmount2 = 0.00;
                    String insertSql = "insert into " + ShiroKit.getUser().getDeal_info() + " (id,customer_id,reservations_id,is_do,pay_service_id,tc_name,service_actual_pay," +
                            "remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,arrears,left_up,left_down,right_up,right_down," +
                            "doctor,id2,order_discount,pay_service_num,deduction_type,primary_amount,discount_hide,whole_discount,deduction_typeName,deduction_amount," +
                            "deposit_amount) values ('" + a4 + UUID + a3 + "'," +
                            "'" + deal.getCustomerId() + "','" + deal.getReservationsId() + "','3','" + deal.getPayServiceId() + "','" + tcName + "'," + repairArrearsAmount2 + ",'" + remark + "'," +
                            "'已开单','" + deal.getOperationTime() + "','" + time + "','" + ShiroKit.getUser().getOutpatientName() + "'," + deal.getFoldingPay() + "," +
                            "" + deal.getPayService() + "," + repairArrearsAmount2 + ",'" + deal.getLeftUp() + "','" + deal.getLeftDown() + "','" + deal.getRightUp() + "','" + deal.getRightDown() + "'," +
                            "'" + doctor + "','" + deal.getId2() + "'," + deal.getOrderDiscount() + "," + deal.getPayServiceNum() + ",'" + deal.getDeductionType() + "'," + deal.getPrimaryAmount() + "," +
                            "" + deal.getDiscountHide() + "," + deal.getWholeDiscount() + ",'" + deal.getDeductionTypeName() + "'," +
                            "" + deal.getDeductionAmount() + "," + deal.getDepositAmount() + ")";
                    result += sqlMapper.insert(insertSql);
                }
            }
        } else {
            result = -1;            //
        }
        resultMap.put("result", resultMap);
        return resultMap;
    }

    @Override
    public Map<String, Object> selectDealInfoByCheck(Map<String, Object> map) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<PayServicedInfo> list = dao.selectDealInfoByCheck(map);
        for (int i = 0; i < list.size(); i++) {
            List<PayServicedInfo> dealList = getDealInfoList(list.get(i).getOperationTime(), list.get(i).getReservationsId());
            list.get(i).setDealList(dealList);
            list.get(i).setDocumentNumber(dealList.get(0).getDocumentNumber());
        }
        resultMap.put("list", list);
        return resultMap;
    }

    public List<PayServicedInfo> getDealInfoList(String operationTime, String reservationsId) throws Exception {
        if (ToolUtil.isEmpty(operationTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sqlresrvations = "select id from reservations_info where id='" + reservationsId + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsInfo.getId() + "' and status=1 ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String rechargeTables = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsId + "' ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsId + "' ";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsId + "' union ";
                rechargeTables += "select * from " + head + "recharge_info where reservations_id='" + reservationsId + "' union ";
            }
        }
        String sql = "select t1.id as id,t1.outpatient_name as outpatientName,left(t1.get_time,19) as getTime,t1.is_do as isDo,t1.deal_status as dealStatus," +
                "t1.doctor1 as doctor,t1.nurse1 as nurse,t1.order_discount as orderDiscount,t1.deductionAmount as deductionAmount,t1.remarks as remarks,t1.serviceActualPay as serviceActualPay," +
                "t2.recharge_people as rechargePeople,t2.checkout_method as checkoutMethod," +
                "t2.document_number as documentNumber,t1.tc_name as tcName,left(t1.operation_time,19) as operationTime from (select t.id2 as id,t.outpatient_name as outpatient_name," +
                "t.get_time as get_time,t.tc_name as tc_name,t.is_do as is_do,t.deal_status as deal_status,GROUP_CONCAT(DISTINCT t.doctor) AS doctor1,GROUP_CONCAT(DISTINCT t.nurse) AS nurse1,(sum(t.service_actual_pay)+sum(t.deposit_amount)) as serviceActualPay," +
                "t.order_discount as order_discount,sum(t.deduction_amount) as deductionAmount,t.remarks as remarks,t.operation_time as operation_time from (" + dealTables + ") t where t.operation_time='" + operationTime + "' and t.reservations_id " +
                "= '" + reservationsId + "' and t.deal_status='已结账' group by t.get_time) t1 left join " + "(select b.recharge_people as recharge_people," +
                "b.document_number as  document_number,group_concat(distinct b.checkout_method) as checkout_method, b.operation_time as operation_time from (" + rechargeTables + ") b " +
                "group by b.operation_time) t2 on t1.get_time = t2.operation_time order by t1.get_time desc";
        List<PayServicedInfo> payServiceList = sqlMapper.selectList(sql, PayServicedInfo.class);
        return payServiceList;
    }

    public List<ConsultantInfo> selectDiagnosisById(String customerId) {
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where customer_id='" + customerId + "'";
        List<ConsultantInfo> list = sqlMapper.selectList(sql, ConsultantInfo.class);
        return list;
    }

    public List<ConsultantInfo> getConsultantInfoList(String reservationsId) {
        String sql = "select id as id, customer_id as customerId,left(diagnosis_time,19) as diagnosisTime," +
                "left(diagnosis_time,11) as diagnosisTimeOne,substring(diagnosis_time,12,10) as diagnosisTimeTwo," +
                "diagnosis_content as diagnosisContent,reservations_id as reservationsId,tc_name as tcName " +
                "from tc_diagnosis_info where reservations_id='" + reservationsId + "' order by diagnosis_time desc";
        List<ConsultantInfo> list = sqlMapper.selectList(sql, ConsultantInfo.class);
        return list;
    }

    public List<ConsultantInfo> getConsultantInfoList2(String reservationsId) {
        String sql = "select id as id, customer_id as customerId,left(diagnosis_time,19) as diagnosisTime, " +
                "left(diagnosis_time,11) as diagnosisTimeOne,substring(diagnosis_time,12,10) as diagnosisTimeTwo," +
                "diagnosis_content as diagnosisContent,reservations_id as reservationsId,tc_name as tcName " +
                "from tc_diagnosis_info where reservations_id='" + reservationsId + "' order by diagnosis_time asc";
        List<ConsultantInfo> list = sqlMapper.selectList(sql, ConsultantInfo.class);
        return list;
    }

    public List<AddVisitedInfo> getRevisitRecordList(String reservationsId) {
        String sql = "select id as id, reservations_id as reservationsId,revisit_time as revisitTime " +
                "from return_visit_info where reservations_id='" + reservationsId + "' order by revisit_time desc";
        List<AddVisitedInfo> list = sqlMapper.selectList(sql, AddVisitedInfo.class);
        return list;
    }

    @Override
    public List<CustomerInfo> consultantExportt(SearchCustomerInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartArrivalTime())) {
            params.put("startArrivalTime", searchInfo.getStartArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndArrivalTime())) {
            params.put("endArrivalTime", searchInfo.getEndArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerStatus())) {
            if ("未设置回访".equals(searchInfo.getCustomerStatus())) {
                params.put("customerStatus", "新客首次");
                params.put("firstReturnSettings", '0');
            } else {
                params.put("customerStatus", searchInfo.getCustomerStatus());
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getDiagnosisStatus())) {
            params.put("diagnosisStatus", searchInfo.getDiagnosisStatus());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFieldTc())) {
            params.put("fieldTc", searchInfo.getFieldTc());
        }
        if (StringUtil.isNotEmpty(searchInfo.getTreatmentUnit())) {
            params.put("treatmentUnit", searchInfo.getTreatmentUnit());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFollowStatus())) {
            String followStatus = "";
            String followStatus2[] = searchInfo.getFollowStatus().split(",");
            if (followStatus2.length == 1) {
                followStatus = followStatus2[0];
            } else {
                for (int i = 0; i < followStatus2.length; i++) {
                    if (i == (followStatus2.length - 1)) {
                        followStatus += "'" + followStatus2[i];
                    } else if (i == 0) {
                        followStatus += followStatus2[i] + "'" + ",";
                    } else {
                        followStatus += "'" + followStatus2[i] + "'" + ",";
                    }
                }
            }
            params.put("followStatus", " ('" + followStatus + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getConsumptionStatus())) {
            String consumptionStatus = "";
            String consumptionStatus2[] = searchInfo.getConsumptionStatus().split(",");
            if (consumptionStatus2.length == 1) {
                consumptionStatus = consumptionStatus2[0];
            } else {
                for (int i = 0; i < consumptionStatus2.length; i++) {
                    if (i == (consumptionStatus2.length - 1)) {
                        consumptionStatus += "'" + consumptionStatus2[i];
                    } else if (i == 0) {
                        consumptionStatus += consumptionStatus2[i] + "'" + ",";
                    } else {
                        consumptionStatus += "'" + consumptionStatus2[i] + "'" + ",";
                    }
                }
            }
            params.put("consumptionStatus", " ('" + consumptionStatus + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getDealStatus())) {
            if ("已结账".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已结账'");
            } else if ("已开单".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已开单'");
            } else {
                params.put("dealStatus", "t.deal_status ='未开单'");
            }
        }
        params.put("tableName", ShiroKit.getUser().getCustomer_info());
        params.put("tableName1", ShiroKit.getUser().getDeal_info());
        return dao.getQueryPagesExport(params);
    }
}